from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.template import loader

# 1. 封装获取激活邮箱链接的函数
def get_email_active_url(request):
    # 1.1 生成包含用户标识的token：aaabbbccc
    user = request.user
    user_info = {'user_id': user.id, 'email': user.email}
    ser = Serializer(settings.SECRET_KEY, expires_in=3600)
    token = ser.dumps(user_info).decode()

    # 1.2 拼接出激活邮箱的链接：
    #     http://www.meiduo.site/success_verify_email.html?token=aaabbbccc
    verify_url = '{}://{}{}?token={}'.format(
        request.scheme, request.META.get('HTTP_HOST'),
        settings.EMAIL_VERIFY_URL_PATH,
        token
    )
    return verify_url


# 2. 得到激活邮件的网页模板的函数
def get_email_active_html(email, verify_url):
    # 1. 得到一个模板对象
    template = loader.get_template('email_active.html')
    # 2. 定义一个上下文对象
    context = {
        'email': email,
        'verify_url': verify_url
    }
    # 3. 利用模板对象的render方法进行动态渲染，得到结果
    return template.render(context)
